<template>
  <div class="login-page">
    <div class="overlay">
      <div class="login-container">
        <!-- 登录标题 + 身份选择 在同一行居中 -->
        <div class="title-row">
          <h2 class="login-title">登录</h2>
          <select v-model="userSystemRole" required class="identity-select">
            <option disabled value="">谁要登录？</option>
            <option value="student">学生</option>
            <option value="teacher">老师</option>
            <option value="admin">管理员</option>
          </select>
        </div>

        <form @submit.prevent="handleLogin" class="login-form">
          <!-- 用户名输入框 -->
          <input
            v-model="userName"
            type="text"
            placeholder="用户名"
            required
            autocomplete="userName"
          />

          <div class="email-group">
            <input v-model="email" type="email" placeholder="邮箱" required />
            <button
              class="get-code-btn"
              type="button"
              :disabled="countdown > 0 || !email"
              @click="sendCode"
            >
              {{ countdown > 0 ? countdown + "秒后重试" : "获取验证码" }}
            </button>
          </div>

          <!-- 📍验证码输入框，独立一行 -->
          <input v-model="code" type="text" placeholder="验证码" required />

          <input
            v-model="passWord"
            type="passWord"
            placeholder="密码"
            required
            autocomplete="current-password"
          />

          <div class="btn-group">
            <button :disabled="!userName || !email || !passWord" type="submit">
              登录
            </button>
            <button type="button" class="register-btn" @click="goToRegister">
              注册
            </button>
          </div>
        </form>

        <!-- 登录成功后显示用户 ID -->
        <p v-if="userId">欢迎，用户ID：{{ userId }}</p>
      </div>

      <!-- ✅ 备案号固定在底部 -->
      <a
        class="beian"
        href="https://beian.miit.gov.cn"
        target="_blank"
        rel="noopener noreferrer"
      >
        蜀ICP备2025153231号-1
      </a>
    </div>
  </div>
</template>



<script setup>
import { ref, onMounted, onBeforeUnmount } from "vue";
import { useRouter } from "vue-router";
import { login, sendCodeApi } from "../api/auth";

const userName = ref("");
const email = ref("");
const passWord = ref("");
const userId = ref("");
const code = ref(""); // 验证码
const userSystemRole = ref("");

const router = useRouter();

const countdown = ref(0);
let timer = null;

// 发送验证码按钮逻辑
const sendCode = async () => {
  if (!email.value) {
    alert("请输入邮箱");
    return;
  }
  try {
    await sendCodeApi(email.value);
    alert("验证码发送成功，请检查邮箱");
    countdown.value = 60;
    timer = setInterval(() => {
      countdown.value--;
      if (countdown.value <= 0) {
        clearInterval(timer);
      }
    }, 1000);
  } catch (err) {
    alert("验证码发送失败：" + err.message);
  }
};

// 登录处理
const handleLogin = async () => {
  if (!userSystemRole.value) {
    alert("请选择身份");
    return;
  }
  try {
    const res = await login({
      userName: userName.value,
      email: email.value,
      passWord: passWord.value,
      code: code.value,
      userSystemRole: userSystemRole.value,
    });

    const token = res.data.token;
    const userIdFromServer = res.data.userId;
    const userNameFromServer = res.data.userName;
    const roleFromServer = res.data.userSystemRole;

    if (token) {
      localStorage.setItem("token", token);
      localStorage.setItem("userId", userIdFromServer);
      localStorage.setItem("userName", userNameFromServer);
      localStorage.setItem("userSystemRole", roleFromServer);
    }

    const role = (roleFromServer || "").trim().toLowerCase();

    switch (role) {
      case "student":
        router.push("/api/user/StudentRedirectPage");
        break;
      case "teacher":
        router.push("/api/user/TeacherRedirectPage");
        break;
      case "admin":
        router.push("/api/user/AdminRedirectPage");
        break;
      default:
        alert("未知身份类型，请联系管理员");
    }
  } catch (err) {
    console.error("登录失败", err);
    alert("登录失败，请检查信息或验证码");
  }
};

// 组件卸载时清理定时器
onBeforeUnmount(() => {
  if (timer) clearInterval(timer);
});

onMounted(() => {
  const token = localStorage.getItem("token");
  if (token) {
    console.log("已登录");
  }
});

const goToRegister = () => {
  router.push("/api/user/register");
};
</script>





<style scoped>
.title-row {
  display: flex;
  justify-content: center; /* 居中整体 */
  align-items: center; /* 垂直居中对齐 */
  margin-bottom: 20px;
  gap: 10px; /* 间距可调 */
}

.login-title {
  margin: 0;
  font-size: 24px;
}

.identity-select {
  height: 32px;
  font-size: 14px;
  padding: 4px 8px;
  border: 1px solid #ccc;
  border-radius: 6px;
}

.beian {
  position: absolute;
  bottom: 20px;
  width: 100%;
  text-align: center;
  font-size: 13px;
  color: #000000;
  z-index: 10;
  text-decoration: none;
}

.login-page {
  position: relative;
  width: 100%;
  height: 100vh;
  background: url("../assets/gao.png") no-repeat center center;
  background-size: cover;
}

.overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.login-container {
  max-width: 400px;
  width: 100%;
  padding: 30px;
  border-radius: 12px;
  background-color: white;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  text-align: center;
}

.login-form input {
  display: block;
  width: 100%;
  padding: 12px;
  margin: 14px 0;
  border: 1px solid #ccc;
  border-radius: 6px;
  font-size: 14px;
}

.btn-group {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}

.login-form button,
.register-btn {
  flex: 1;
  padding: 10px;
  margin: 0 5px;
  background-color: #409eff;
  border: none;
  border-radius: 4px;
  color: white;
  font-weight: bold;
  cursor: pointer;
  transition: background-color 0.3s;
}

.login-form button:disabled {
  background-color: #a0cfff;
  cursor: not-allowed;
}

.login-form button:not(:disabled):hover,
.register-btn:hover {
  background-color: #66b1ff;
}

.email-group {
  display: flex;
  align-items: center;
  margin: 14px 0;
}

.email-group input {
  flex: 1;
  height: 44px;
  padding: 10px 12px;
  font-size: 14px;
  border: 1px solid #ccc;
  border-right: none;
  border-radius: 6px 0 0 6px;
  outline: none;
  transition: border 0.2s ease-in-out;
}

.email-group input:focus {
  border-color: #409eff;
}

.get-code-btn {
  height: 44px;
  padding: 0 16px;
  font-size: 14px;
  white-space: nowrap;
  background-color: #409eff;
  color: white;
  border: 1px solid #409eff;
  border-radius: 0 6px 6px 0;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.get-code-btn:hover:not(:disabled) {
  background-color: #66b1ff;
}

.get-code-btn:disabled {
  background-color: #d3dce6;
  border-color: #d3dce6;
  cursor: not-allowed;
  color: #fff;
}
.login-form input {
  display: block;
  width: 100%;
  height: 44px;
  padding: 12px;
  margin: 14px 0;
  border: 1px solid #ccc;
  border-radius: 6px;
  font-size: 14px;
  box-sizing: border-box;
}
</style>
